//
// Created by sgyt on 2020/6/30.
//
#define _XOPEN_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>

#if defined(ELF_NOTE_SOLARIS)
#include <stropts.h>
#endif


int ptym_open(char *pts_name,int pts_namesz)
{
    //伪终端名称
    char *ptr;

    //打开的伪终端描述符
    int fdm;

    //错误描述
    int err;

    if((fdm = posix_openpt(O_RDWR))<0)
    {
        return -1;
    }

    if(grantpt(fdm) < 0)
    {
        goto errout;
    }

    if(unlockpt(fdm) < 0)
    {
        goto errout;
    }

    if((ptr = ptsname(fdm)) == NULL )
    {
        goto errout;
    }

    strncpy(pts_name,ptr,pts_namesz);
    pts_name[pts_namesz - 1] = '\0';
    return fdm;

    errout:
        err = errno;
        close(fdm);
        errno = err;
        return -1;

}

int ptys_open(char *pts_name)
{
    int fds;
    int setup,err;

    if((fds = open(pts_name,O_RDWR)) < 0)
    {
        return -1;
    }

    if(setup = ioctl(fds,I_FND,"ldterm") < 0 )
    {
        goto errout;
    }

    if(setup == 0)
    {
        if(ioctl(fds,I_PUSH,"ptem") < 0)
        {
            goto errout;
        }

        if(ioctl(fds,I_PUSH,"Idterm") < 0)
        {
            goto errout;
        }

        if(ioctl(fds,I_PUSH,"ttcompat") < 0)
        {
            goto errout;
        }
    }


    errout:
    err = errno;
    close(fds);
    errno = err;
    return -1;
}

int main(int argc,char *argv[])
{
    char *pts_name = NULL;
    int size = 4;
    ptym_open(pts_name,size);
    printf("sssss");
    return 0;
}
